// src/interceptor/transform.interceptor.ts
import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Logger } from '../../utils/log4js';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  static readonly whiteList = ['/', '/uploads', '/static', 'nest-web']; //白名单
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.getArgByIndex(1).req;
    console.log('拦截器', req.url);
    if (
      req.url.startsWith('/nest-vue-short-passage') ||
      req.url.startsWith('/nest-status') ||
      TransformInterceptor.whiteList.includes(req.url)
    ) {
      return next.handle();
    }
    return next.handle().pipe(
      map((data) => {
        const logFormat = ` <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        Request original url: ${req.originalUrl}
        Method: ${req.method}
        IP: ${req.ip}
        User: ${JSON.stringify(req.user)}
        Response data:\n ${JSON.stringify(data)}
        <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<`;
        Logger.access(logFormat);
        Logger.log(logFormat);
        console.log('全局响应拦截器方法返回内容后...');
        return {
          code: 200,
          timestamp: new Date().toISOString(),
          path: req.url,
          message: '成功',
          data: data,
        };
      }),
    );
  }
}
